package com.aims.server.service.impl;

import com.aims.common.exception.BizException;
import com.aims.common.model.PageResult;
import com.aims.server.dao.mapper.CertificateMapper;
import com.aims.server.domain.Certificate;
import com.aims.server.domain.dto.CertificateQueryDTO;
import com.aims.server.domain.dto.CertificateSaveDTO;
import com.aims.server.domain.vo.CertificateVO;
import com.aims.server.service.CertificateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 证书信息Service实现类
 */
@Service
public class CertificateServiceImpl implements CertificateService {

    @Resource
    private CertificateMapper certificateMapper;

    /**
     * 分页查询证书列表
     *
     * @param queryDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<CertificateVO> pageList(CertificateQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Certificate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Certificate::getDataStatus, 1);

        // 开户机构条件查询
        if (StringUtils.hasText(queryDTO.getAcctInstitutionCode())) {
            queryWrapper.eq(Certificate::getAcctInstitutionCode, queryDTO.getAcctInstitutionCode());
        }

        // 按更新时间倒序
        queryWrapper.orderByDesc(Certificate::getUpdatedDate);

        // 分页查询
        Page<Certificate> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<Certificate> pageResult = certificateMapper.selectPage(page, queryWrapper);

        // 转换为VO
        List<CertificateVO> voList = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return PageResult.of(voList, pageResult.getTotal(), pageResult.getCurrent(), pageResult.getSize());
    }

    /**
     * 新增或编辑证书
     *
     * @param saveDTO 保存数据
     */
    @Override
    public void saveOrUpdate(CertificateSaveDTO saveDTO) {
        // 唯一性校验：开户机构+账户分类+证书ID
        checkUniqueness(saveDTO);

        Certificate certificate = new Certificate();
        BeanUtils.copyProperties(saveDTO, certificate);

        if (saveDTO.getId() == null) {
            // 新增
            certificate.setDataStatus(1);
            certificateMapper.insert(certificate);
        } else {
            // 编辑
            Certificate existCertificate = certificateMapper.selectById(saveDTO.getId());
            if (existCertificate == null || existCertificate.getDataStatus() == 0) {
                throw new BizException("证书信息不存在或已删除");
            }
            certificateMapper.updateById(certificate);
        }
    }

    /**
     * 删除证书（逻辑删除）
     *
     * @param id 证书ID
     */
    @Override
    public void delete(Long id) {
        Certificate certificate = certificateMapper.selectById(id);
        if (certificate == null || certificate.getDataStatus() == 0) {
            throw new BizException("证书信息不存在或已删除");
        }

        // 逻辑删除：将数据状态设置为0
        certificate.setDataStatus(0);
        certificateMapper.updateById(certificate);
    }

    /**
     * 唯一性校验：开户机构+账户分类+证书ID
     *
     * @param saveDTO 保存数据
     */
    private void checkUniqueness(CertificateSaveDTO saveDTO) {
        LambdaQueryWrapper<Certificate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Certificate::getAcctInstitutionCode, saveDTO.getAcctInstitutionCode())
                .eq(Certificate::getAcctType, saveDTO.getAcctType())
                .eq(Certificate::getDataStatus, 1);

        // 证书ID可能为空，需要特殊处理
        if (StringUtils.hasText(saveDTO.getCerificateId())) {
            queryWrapper.eq(Certificate::getCerificateId, saveDTO.getCerificateId());
        } else {
            queryWrapper.isNull(Certificate::getCerificateId);
        }

        // 编辑时排除当前记录
        if (saveDTO.getId() != null) {
            queryWrapper.ne(Certificate::getId, saveDTO.getId());
        }

        Long count = certificateMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BizException("该开户机构、账户分类和证书ID的组合已存在");
        }
    }

    /**
     * 实体转换为VO
     *
     * @param certificate 实体
     * @return VO
     */
    private CertificateVO convertToVO(Certificate certificate) {
        CertificateVO vo = new CertificateVO();
        BeanUtils.copyProperties(certificate, vo);
        return vo;
    }
}